package com.jdy.haoduoai.util;

import android.content.Context;
import android.net.ParseException;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.intface.IResponseListener;
import com.jdy.haoduoai.rx.util.async.Async;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.schedulers.Schedulers;

/**
 * Http utils for get and post http request and handle response. This class is
 * created for easy the use of interface on using xiaoxiaoban.
 * 
 * @author zp @ 2015-5-19 上午9:28:20
 */

public class HttpUtils {

  /**
   * Global
   */
  public static final String TAG = "HttpUtils";
  public static boolean USE_SYSTEM_CACHE = true;// default mechanism for cache.

  private static final int TIMEOUT = 10000;

  public static final int PORT = 80;
//  public static String HTTP_DOMAIN = "http://api.zhuanzhuan888.com/";
  public static String HOST_API = "http://sapi.jdy520.com"; // "http://xiaoxiaoban.zhuanzhuan888.com";
//  public static final String HOST_API_DEBUG = "http://192.168.1.93";
  // public static final String HOST_API = "http://192.168.1.173:" + PORT;
  // public static final String HOST_API = "http://192.168.1.173:" +
  // PORT;
//  public static final String HOST_RTMP = "rtmp://114.215.186.231:1935/";
//  public static final String HOST_VOICE_RESOURCE = "http://api.zhuanzhuan888.com/upload/chat/";
  public static final String HOST_RESOURCE = HOST_API + "/"; // :"http://www.zhuanzhuan888.com/lexiaobao/"
  public static final String API_URL = HOST_API;

  public static final String RTMP_URL = "rtmp://12831.mpull.live.lecloud.com/live/";

  public static final String KEY = "0CDQMgmciERvvJ46RJ0iY6gzZ1HEiO9n";
  public static final String MANUFACTURE_VERSION = "1.3.6";

  public static final String HTTP_LOGIN = HOST_API + "/api/2.0/member/login?"; // login
  public static final String HTTP_GETCODE = HOST_API + "/api/2.0/member/code?"; // getVerifyCode
  public static final String HTTP_REGISTER = HOST_API
      + "/api/2.0/member/register?"; // register
  // Outcome keyword tags
  public static final String TAG_CODE_O = "code";
  public static final String TAG_DATA_O = "data";
  public static final String TAG_STATUS_O = "status";

  // Income keyword tags
  public static final String TAG_MOBILE_I = "mobile";
  public static final String TAG_MODULE_I = "module";
  public static final String TAG_PWD_I = "password";
  public static final String TAG_KEY_I = "key";
  public static final String TAG_CHANNEL_I = "channel";
  public static final String TAG_BANNER_ID_I = "Banner_id";
  public static final String TAG_STATUS_I = "status";
  public static final String TAG_PRODUCT_ID_I = "product_id";
  public static final String TAG_PAY_METHOD_I = "pay_method";
  public static final String TAG_MACID_I = "macid";
  public static final String TAG_VERIFY_CODE_I = "code";
  public static final String TAG_AGE_I = "age";
  public static final String TAG_APPELLATION_NAME_I = "callname";
  public static final String TAG_NICK_NAME_I = "nickname";
  public static final String TAG_HEAD_IMAGE_I = "head";
  public static final String TAG_PLATFORM_I = "platform";
  public static final String TAG_TOKEN_I = "token";
  public static final String TAG_SNO_I = "sno";
  public static final String TAG_CATALOG_I = "catalog";
  public static final String TAG_AVATAR_I = "avatar";
  public static final String TAG_MAC_ID_I = "machine_id";
  public static final String TAG_BABY_NAME_I = "name";
  public static final String TAG_NAME_I = "name";
  public static final String TAG_BABY_BIRTH_I = "dob";
  public static final String TAG_GENDER_I = "gender";
  public static final String TAG_ACTIVATION_NO_I = "serial_no";
  public static final String TAG_POWER_ID_I = "power";
  @Deprecated
  public static final String TAG_VOLUMN_I = "volumn";
  public static final String TAG_VOLUME = "volume";
  public static final String TAG_UID_I = "uid";
  public static final String TAG_VERSION_I = "version";
  public static final String TAG_DISCSIZE_I = "discsize";
  public static final String TAG_USESIZE_I = "usesize";
  public static final String TAG_CLOSE_TIME_I = "closetime";
  public static final String TAG_LIGHT_OPEN_I = "lightopen";
  public static final String TAG_PLAYLISTIDX_I = "playlistidx";
  public static final String TAG_PLAYDIS_I = "playdis";
  public static final String TAG_PLAYUPTIME_I = "playuptime";
  public static final String TAG_DOWNLOADED_I = "downloaded";
  public static final String TAG_PAGE_SIZE_I = "page_size";
  public static final String TAG_PAGE_I = "page";
  public static final String TAG_TAG_I = "tag";
  public static final String TAG_TITLE_I = "title";
  public static final String TAG_QUESTION_I = "question";
  public static final String TAG_VIDEO_ID_I = "id";
  public static final String TAG_SHARE_STORY_ID_I = "id";
  public static final String TAG_STORY_ID_I = "rid";
  public static final String TAG_STORY_I = "stroy";
  public static final String TAG_CHAT_VOICE_FILE_I = "chat";
  public static final String TAG_FROMTO_I = "fromto";
  public static final String TAG_FILE_TIME_I = "filetime";
  public static final String TAG_TIME_STAMP_I = "ctime";
  public static final String TAG_ACTION_I = "act";
  public static final String TAG_OPERATION_I = "op";
  public static final String TAG_MINUTE_I = "seconds";
  public static final String TAG_PLAY_MODE = "ptype";
  public static final String TAG_MINUTES_I = "minutes";
  public static final String TAG_ACT_PLAY_I = "play";
  public static final String TAG_ACT_INIT_I = "init";
  public static final String TAG_ACT_CLEAN_I = "clean";
  public static final String TAG_ACT_VOLUMNE_I = "volume";
//  public static final String TAG_ACT_LIGHT_I = "light";
  public static final String TAG_ACT_POWER_I = "power";
  public static final String TAG_ACT_TIMEINGOFF_I = "timingoff";
  public static final String TAG_OP_CONTROL_I = "control";
  public static final String TAG_OP_ON_I = "on";
  public static final String TAG_OP_OFF_I = "off";
  public static final String TAG_OP_CARTOON_I = "cartoon";
  public static final String TAG_OP_STORY_I = "story";
  public static final String TAG_OP_PAUSE_I = "pause";
  public static final String TAG_OP_CONTINUE_I = "continue";
  public static final String TAG_OP_VIDEOS_I = "videos";
  public static final String TAG_OP_SPEED_I = "speed";
  public static final String TAG_OP_REWEIND_I = "rewind";
  public static final String TAT_OP_TURNOFF_DEVICE_I = "off";
  public static final String TAG_TYPE_I = "type";
  public static final String TAG_CATEGORY_ID_I = "category_id";
  public static final String TAG_COLLECTION_NAME_I = "name";
  public static final String TAG_ALBUM_ID_I = "id";
  public static final String TAG_COLLECTION_ID_I = "collection_id";
  public static final String TAG_DUB_STORY_ID_I = "id";
  public static final String TAG_LIKE_I = "zan";
  public static final String TAG_DISLIKE_I = "cai";
  public static final String TAG_COMMENT_CONTENT_I = "content";
  public static final String TAG_SHARE_DUB_ID_I = "dubid";
  public static final String TAG_COMMENT_ID_I = "dfcid";
  public static final String TAG_OS_TYPE_I = "type";
  public static final String TAG_APP_VERSION_I = "app_version";
  public static final String TAG_PROBLEM_DESCRIPTION_I = "content";

  // request methods
  public static final String TAG_POST_REQUEST = "POST";
  public static final String TAG_GET_REQUEST = "GET";
  public static final String TAG_DELETE_REQUEST = "DELETE";
  public static final String TAG_PUT_REQUEST = "PUT";

  // Login
  public static final String LOGIN_METHOD_POST = "/api/2.0/member/login_encrypt";
  // Register
  public static final String GET_VERIY_CODE_METHOD_GET = "/api/2.0/member/code_encrypt";
  public static final String REGISTER_METHOD_POST = "/api/2.0/member/register_encrypt";

  // Update
  public static final String UPDATE_PARENT_METHOD_PUT = "/api/2.0/member/";// the

  // 获取早教支招列表
  public static final String GET_EarlyClass_list = "/api/2.0/member/consult";
  // 提交早教问题、
  public static final String SUBMIT_QUESTION_POST = "/api/2.0/member/consult";
  // get hot key
  public static final String HOT_SEARCH_GET = "/api/2.0/catalog/search";
  // 获取动画片
  public static final String GET_CATALOG_ALBUM = "/api/2.0/catalog/album";
  // 专辑的小集
  public static final String GET_EPISODE_LIST = "/api/2.0/catalog/episode";
  // 评论列表
  public static final String GET_COMMENT_LIST = "/api/2.0/member/comment";
  // 获取故事资源
  public static final String GET_STORY_LIST = "/api/2.0/catalog/story";
  // formal
  // format
  // should
  // be
  // "/api/user/{$sno}"

  // Upload avatar
  public static final String UPLOAD_AVATAR_METHOD_POST = "/api/2.0/uploader";
  // Modify passward
  public static final String MODIFY_PASSWARD_METHOD_POST = "/api/2.0/member/change-password";
  // Get detail user information
  public static final String GET_USER_DETAIL_METHOD_GET = "/api/2.0/member/";// the
  // formal
  // format
  // should
  // be
  // "/api/user/{$sno}"
  // Logout
  // public static final String LOGOUT_METHOD_POST = "/api/uesr/logout";
  // Register baby
  // public static final String REGISTER_BABY_METHOD_POST =
  // "/api/baby/register";
  // Get baby information
  // public static final String GET_BABY_METHOD_GET = "/api/baby/";//
  // /api/baby/{$id}
  // Update baby information
  public static final String UPDATE_BABY_METHOD_PUT = "/api/2.0/member/machine/";// /api/baby/{$id}
  // Upload baby avatar
  public static final String UPLOAD_BABY_AVATAR_POST = "/api/2.0/uploader";

  /**
   * Device
   */
  public static final String BIND_DEVICE_METHOD_POST = "/api/2.0/member/bind";
  public static final String ACTIVATE_DEVICE_METHOD_POST = "/api/machine/activate";
  public static final String GET_DEVICE_DETAIL_GET = "/api/2.0/member/machine/";// /api/machine/{$macId}
  // public static final String CONNECT_DEVICE_METHOD_POST =
  // "/api/machine/connect";
  // public static final String UPDATE_DEVICE_METHOD_PUT = "/api/machine/";//
  // api/machine/{$macId}
  public static final String GET_DOWNLOADED_LIST_METHOD_GET = "/api/2.0/member/downloaded";
  public static final String GET_NEWEST_DEVICE_VERSION_METHOD_GET = "/api/2.0/machine/version";

  /**
   * Favorite
   */
  public static final String GET_FAVORITES_METHOD_GET = "/api/2.0/member/favorite";
  public static final String ADD_FAVORITE_METHOD_POST = "/api/2.0/member/favorite";
  public static final String DELETE_FAVORITE_METHOD_DELETE = "/api/2.0/member/favorite";// {$id,{,$id}}

  /**
   * Dub
   */
  public static final String GET_DUBS_METHOD_GET = "/api/2.0/member/dub";
  // public static final String ADD_DUB_METHOD_POST = "/api/dub";
  // public static final String ADD_SINGLE_DUB_METHOD_PUT = "/api/dub/";//
  // /api/dub/{$id}
  // public static final String DELETE_DUB_METHOD_DELETE = "/api/dub/";//
  // /api/dub/{$id}

  /**
   * Chat
   */
  public static final String GET_CHAT_METHOD_GET = "/api/2.0/member/chat";
  public static final String SAVE_CHAT_METHOD_POST = "/api/2.0/uploader";
  public static final String DELETE_CHAT_METHOD_DELETE = "/api/2.0/member/chat";// /api/chat/{$uid}
  public static final String TAG_ALL_CHAT = "all";// key word to denotes all
                                                  // chat info.

  /**
   * Device operation
   */

  public static final String OPERATE_DEVICE_METHOD_GET = "/api/2.0/device/op";
  public static final String GET_SIGNATURE_GET = "/api/2.0/member/checkin";

  public static final String GET_TLS_SIG = "/api/2.0/tls/login";

  public static final String GET_PAINPOINT_LIST_GET = "/api/2.0/operation/habit/habits";

  public static final String GET_CUSTOMPAINPOINT_LIST_GET = "/api/2.0/operation/habit/habits_customized";

  public static final String UPDATE_PAINPOINT_POST = "/api/2.0/operation/habit/habits";

  public static final String PUBLISH_COMMENTS_POST = "/api/2.0/operation/habit/{id}/comment";

  public static final String GET_COMMENTS_LIST_GET = "/api/2.0/operation/habit/{id}/comment";

  public static final String LIKE_COMMENT_PUT = "/api/2.0/operation/habit/comment/like";

  /**
   * Content
   */
  // public static final String GET_CATEGORY_CONTENT_METHOD_GET =
  // "/api/category";
  public static final String GET_COLLECTION_METHOD_GET = "/api/2.0/collection";
  public static final String GET_COLLECTION_DETAIL_METHOD_GET = "/api/2.0/collection/";// /api/collection/{$id}
  // public static final String GET_CARTOON_METHOD_GET = "/api/episode";

  /**
   * Share and comments
   */
  // public static final String GET_SHARE_METHOD_GET = "/api/share";
  // public static final String GET_SHARE_DETAIL_METHOD_GET = "/api/share/";//
  // /api/share/{$id}
  // public static final String EVALUATE_SHARE_METHOD_PUT = "/api/share";
  // public static final String GET_SHARE_COMMENT_METHOD_GET =
  // "/api/share/comment";
  // public static final String ADD_SHARE_COMMENT_METHOD_POST =
  // "/api/share/comment";
  // public static final String REPLY_SHARE_COMMENT_METHOD_POST =
  // "/api/share/comment/reply";
  // public static final String GET_SHARE_REPLY_COMMENT_METHOD_GET =
  // "/api/share/comment/reply";
  // public static final String GET_COMMENT_ON_COLLECTION_METHOD_GET =
  // "/api/comment";
  // public static final String ADD_COLLECTION_COMMENT_METHOD_POST =
  // "/api/comment";
  public static final String ADD_TOPIC_REPLY_COMMENT_METHOD_POST = "/api/2.0/operation/topic/reply/comment";
  public static final String FOLLOW_TOPIC_METHOD_POST = "/api/2.0/operation/topic/follow";
  public static final String ADD_HOT_TOPIC_REPLY_METHOD_POST = "/api/2.0/operation/topic/reply";
  public static final String UPLOAD_TOPIC_PICTURES_METHOD_POST = "/api/2.0/uploader";
  /**
   * Rank
   */
  // public static final String GET_STORIES_RANK_METHOD_GET = "/api/rank";
  public static final String FEEDBACK_METHOD_POST = "/api/2.0/system/feedback";
  // public static final String GET_AD_METHOD_GET = "/api/ad";
  // public static final String GET_ROLLING_SLIDER_METHOD_GET = "/api/slider";
  // public static final String GET_NEWEST_APP_VERSION_GET = "/api/version";

  /**
   * Focus
   */
  public static final String FOLLOW_SOMEONE_POST = "/api/2.0/member/follow";
  public static final String GET_FOCUSERS_GET = "/api/2.0/member/following/";
  public static final String GET_FOLLOWERS_GET = "/api/2.0/member/followers";

  /**
   * Calendar
   */
  public static final String GET_MAINPAGE_CALENDAR_GET = "/api/2.0/index/index_new";
  public static final String GET_CALENDARPAGE_GET = "/api/2.0/index/month";
  public static final String GET_CLASSES_GET = "/api/2.0/index/date";

  /**
   * Radio
   */
  // public static final String GET_RADIO_LIST_METHOD_GET = "/api/radio";

  /**
   * Book
   */
  // public static final String GET_BOOK_LIST_METHOD_GET = "/api/book";
  // public static final String GET_BOOK_CATEGORY_DETAILS = "/api/book/";
  // public static final String GET_BOOK_PAGE_LIST = "/api/book/episode";
  // public static final String GET_BOOK_SINGLE_PAGE_DETAIL =
  // "/api/book/episode/";

  /**
   * Banner
   */
  // public static final String CLICK_BANNER_METHOD_POST = "/api/ad/banner";
  public static final String GET_LOCK_STATUS_METHOD_GET = "/api/2.0/machine/getlockstatus";

  // /**
  // * Story
  // */
  // public static final String GET_STORY_DETAIL_METHOD_GET = "/api/story/";
  //
  // /**
  // * Fit cartoon for children
  // */
  // public static final String GET_FIT_CARTOON_METHOD_GET =
  // "/api/collection/fitcartoon";

  /**
   * Pay
   */
  public static final String GET_PAY = "/api/pay";
  public static final String GET_PACKAGES = "/api/2.0/sales/product";
  public static final String GET_ORDER = "/api/order";

  /**
   * Http request interface1 普通http请求(上传文件请使用 startUploadRequest )
   * 
   * @param url
   * @param params
   * @param requestMethod
   * @return
   */
  public static ResponseResult startRequest(String httpUrl,
      Map<String, Object> params, String requestMethod) {
    String realUrl = params2String(httpUrl, params);
    return commonResult(realUrl, requestMethod);
  }

  public static ResponseResult startRequestEncrypt(String httpUrl,
      Map<String, Object> params, String requestMethod) {
    String realUrl = "";
    JSONObject jsonObj = new JSONObject();
    try {
      for (Entry<String, Object> entry : params.entrySet()) {
        if (entry.getKey() == null || entry.getValue() == null) {
          continue;
        }
        jsonObj.put(entry.getKey() + "", entry.getValue() + "");
      }

      String rawData = jsonObj.toString();
      realUrl = Uri.parse(httpUrl).buildUpon()
          .appendQueryParameter("data", AES128.encrypt(rawData)).build()
          .toString();
    } catch (JSONException e) {
      e.printStackTrace();
    }

    return commonResultEncrypt(realUrl, requestMethod);
  }

  public static JSONObject startRequestJsonObj(String httpUrl,
                                               Map<String, Object> params, String requestMethod) {
    String realUrl = params2String(httpUrl, params);
    return commonResultJsonObject(realUrl, requestMethod);
  }

  public static JSONObject commonResultJsonObject(String httpUrl,
                                                  String requestMethodName) {
    Context context = LeXiaoXiaoBanApp.getAppContext();
    try {
      if (Tools.isNetworkAvailable2(context)) {
        JSONObject jsonObj = initiateHttpConnection(httpUrl, requestMethodName);
        LeXiaoXiaoBanLog.e(TAG, jsonObj.toString());
        return jsonObj;
        //  return new ResponseResult(jsonObj);
      } else {
        Toast.makeText(context, "请检查网络连接!", Toast.LENGTH_SHORT).show();
        return null;
      }
    } catch (Exception ex) {
      return null;
    }
  }

  /**
   * Http request interface2
   * 
   * @param httpUrl
   * @param params
   * @param requestMethod
   * @param callback
   */
  public static void startRequest(final String httpUrl,
      final Map<String, Object> params, final String requestMethod,
      final IResponseListener callback) {

    Async.start(new Func0<ResponseResult>() {
      @Override
      public ResponseResult call() {
        String realUrl = params2String(httpUrl, params);
        return commonResult(realUrl, requestMethod);
      }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Action1<ResponseResult>() {
          @Override
          public void call(ResponseResult response) {
            if (callback != null) {
              callback.onRecieveData(response);
            }
          }
        });
  }

  /**
   * upload method 1 上传文件
   * 
   * @param httpUrl
   * @param params
   * @param fileKey
   * @param filePath
   * @param requestMethod
   * @return
   */
  public static ResponseResult startUploadRequest(String httpUrl,
      Map<String, Object> params, String fileKey, String filePath,
      String requestMethod) {
    String realUrl = params2String(httpUrl, params);
    return commonResult4Upload(realUrl, fileKey, filePath, requestMethod);

  }

  /**
   * upload method 2
   * 
   * @param httpUrl
   * @param params
   * @param fileKey
   * @param filePath
   * @param requestMethod
   * @param callback
   */
  public static void startUploadRequest(final String httpUrl,
      final Map<String, Object> params, final String fileKey,
      final String filePath, final String requestMethod,
      final IResponseListener callback) {

    Async.start(new Func0<ResponseResult>() {
      @Override
      public ResponseResult call() {
        String realUrl = params2String(httpUrl, params);
        return commonResult4Upload(realUrl, fileKey, filePath, requestMethod);
      }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Action1<ResponseResult>() {
          @Override
          public void call(ResponseResult response) {
            if (callback != null) {
              callback.onRecieveData(response);
            }
          }
        });
  }

  /**
   * Request methods
   */
  /**
   * Request http request and get the result.
   * 
   * @param httpUrl
   * @param requestMethodName
   * @return
   */
  public static ResponseResult commonResult(String httpUrl,
      String requestMethodName) {
    Context context = LeXiaoXiaoBanApp.getAppContext();
    try {
      if (Tools.isNetworkAvailable2(context)) {
        JSONObject jsonObj = initiateHttpConnection(httpUrl, requestMethodName);
        LeXiaoXiaoBanLog.e(TAG, jsonObj.toString());
        return new ResponseResult(jsonObj);
      } else {
        Toast.makeText(context, "请检查网络连接!", Toast.LENGTH_SHORT).show();
        return null;
      }
    } catch (Exception ex) {
      return null;
    }
  }

  public static ResponseResult commonResultEncrypt(String httpUrl,
      String requestMethodName) {
    Context context = LeXiaoXiaoBanApp.getAppContext();
    try {
      if (Tools.isNetworkAvailable2(context)) {
        JSONObject jsonObj = initiateHttpConnectionEncrypt(httpUrl,
            requestMethodName);
        LeXiaoXiaoBanLog.e(TAG, jsonObj.toString());
        return new ResponseResult(jsonObj);
      } else {
        Toast.makeText(context, "请检查网络连接!", Toast.LENGTH_SHORT).show();
        return null;
      }
    } catch (Exception ex) {
      return null;
    }
  }

  // public static ResponseResult uploadAudioVideoFile(String key, String
  // mobile,
  // String module, File Filedata) {
  // try {
  // String httpURL = null;
  // Uri.Builder b = Uri.parse(API_URL + "/api/2.0/uploader").buildUpon();
  // b.appendQueryParameter("key", key);
  // b.appendQueryParameter("mobile", mobile);
  // b.appendQueryParameter("module", module);
  //
  // httpURL = b.build().toString();
  //
  // String contentString = HttpClientHelper.doPost(httpURL, "Filedata",
  // Filedata.getAbsolutePath());
  //
  // JSONObject resultJson = new JSONObject(contentString);
  // return new ResponseResult(resultJson);
  // } catch (ParseException e) {
  // // TODO Auto-generated catch block
  // e.printStackTrace();
  // } catch (IOException e) {
  // // TODO Auto-generated catch block
  // e.printStackTrace();
  // } catch (JSONException e) {
  // // TODO Auto-generated catch block
  // e.printStackTrace();
  // }
  // return null;
  //
  // }

  /**
   * URLConnection上传接口
   * 
   * @param httpUrl
   * @param fileKey
   *          服务器端通过fileKey得到对应的文件
   * @param fileName
   *          文件的名字，包含后缀名
   * @param requestMethodName
   * @return
   */
  public static ResponseResult commonResult4Upload(String httpUrl,
      String fileKey, String fileName, String requestMethodName) {
    String result = null;

    try {
      int res = 0;

      String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
      String PREFIX = "--", LINE_END = "\r\n";
      String CONTENT_TYPE = "multipart/form-data"; // 内容类型
      String CHARSET = "utf-8";

      URL url;
      try {
        url = new URL(httpUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(TIMEOUT * 5);
        conn.setConnectTimeout(TIMEOUT);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod(requestMethodName);
        conn.setRequestProperty("Charset", CHARSET);
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="
            + BOUNDARY);

        File file = new File(fileName);
        if (file != null) {
          DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

          StringBuffer sb = new StringBuffer();
          sb.append(PREFIX);
          sb.append(BOUNDARY);
          sb.append(LINE_END);

          sb.append("Content-Disposition: form-data; name=\"" + fileKey + "\""
              + ";" + " filename=\"" + file.getName() + "\"" + LINE_END);
          sb.append("Content-Type: application/octet-stream; charset="
              + CHARSET + LINE_END);
          sb.append(LINE_END);
          dos.write(sb.toString().getBytes());

          InputStream is = new FileInputStream(file);
          byte[] bytes = new byte[1024];
          int len = 0;
          while ((len = is.read(bytes)) != -1) {
            dos.write(bytes, 0, len);
          }
          is.close();
          dos.write(LINE_END.getBytes());
          byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
          dos.write(end_data);
          dos.flush();

          // 获取响应码 200=成功 当响应成功，获取响应的流
          res = conn.getResponseCode();
          if (res == 200) {
            InputStream input = conn.getInputStream();
            StringBuffer sb1 = new StringBuffer();
            int ss;
            while ((ss = input.read()) != -1) {
              sb1.append((char) ss);
            }
            result = sb1.toString();
            Log.e(TAG, "result : " + result);
          } else {
            Log.e(TAG, "request error");
          }
        }
      } catch (MalformedURLException e) {
        e.printStackTrace();
      } catch (ProtocolException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }

    } catch (ParseException e) {
      e.printStackTrace();
    }

    try {
      Context context = LeXiaoXiaoBanApp.getAppContext();
      if (Tools.isNetworkAvailable2(context) && Tools.isNotEmpty(result)) {
        JSONObject jsonObj = new JSONObject(result);
        return new ResponseResult(jsonObj);
      } else {
        Toast.makeText(context, "请检查网络连接!", Toast.LENGTH_SHORT).show();
        return null;
      }
    } catch (Exception ex) {
      return null;
    }
  }

  /**
   * 拼接参数
   * 
   * @param httpUrl
   * @param params
   * @return
   */
  public static String params2String(String httpUrl, Map<String, Object> params) {
    ArrayList<HashMap<String, String>> postParams = new ArrayList<HashMap<String, String>>();

    for (Entry<String, Object> entry : params.entrySet()) {
      if (entry.getKey() == null || entry.getValue() == null) {
        continue;
      }
      HashMap<String, String> param = new HashMap<String, String>();
      param.put(entry.getKey(), entry.getValue() + "");
      postParams.add(param);
    }

    String target = null;
    StringBuffer temp = new StringBuffer();
    for (HashMap<String, String> map : postParams) {
      Iterator<String> iter;
      iter = map.keySet().iterator();
      while (iter.hasNext()) {
        String key = iter.next();
        String value = map.get(key);
        temp.append(key);
        temp.append('=');
        try {
          temp.append(URLEncoder.encode(value, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        }
        temp.append('&');
      }
    }
    if (temp.length() > 1) {
      temp.deleteCharAt(temp.length() - 1);
    }

    target = temp.toString();

    String realUrl;

    if (postParams.size() > 0) {
      if (httpUrl.indexOf('?') > 0) {
        realUrl = httpUrl + "&" + target;
      } else {
        realUrl = httpUrl + "?" + target;
      }
    } else {
      realUrl = httpUrl;
    }

    return realUrl;
  }

  public static final JSONObject initiateHttpConnectionEncrypt(String myurl,
      String methodName) throws IOException, JSONException {
    LeXiaoXiaoBanLog.e(TAG, "URL:" + myurl);
    LeXiaoXiaoBanLog.e(TAG, "REQUEST METHOD:" + methodName);

    InputStream is = null;
    String contentAsString = "";// = convertStreamToString(is);
    HttpURLConnection conn = null;
    try {
      int splitIndex = myurl.indexOf('?');
      String urlPart = myurl.substring(0, splitIndex);
      String argumentPart = myurl.substring(splitIndex + 1, myurl.length());
      URL url = new URL(myurl);
      LeXiaoXiaoBanLog.e(TAG, urlPart.toString());
      LeXiaoXiaoBanLog.e(TAG, argumentPart.toString());
      conn = (HttpURLConnection) url.openConnection();
      conn.setReadTimeout(TIMEOUT * 5 /* milliseconds */);
      conn.setConnectTimeout(TIMEOUT /* milliseconds */);
      conn.setRequestMethod(methodName);
      conn.setUseCaches(USE_SYSTEM_CACHE);
      LeXiaoXiaoBanLog.e(TAG, methodName);
      conn.setDoInput(true);
      // conn.setDoOutput(true);
      conn.setInstanceFollowRedirects(false);
      // Starts the query
      try {
        // DataOutputStream wr = new DataOutputStream(conn.getOutputStream ());
        // wr.writeBytes(argumentPart);
        // wr.flush();
        // wr.close();
        conn.connect();
        int response = conn.getResponseCode();
        LeXiaoXiaoBanLog.e(TAG, "The response is: " + response);
        is = conn.getInputStream();
        // Convert the InputStream into a string
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,
            "UTF-8"), 1024);
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null) {
          sb.append(line + "\n");
        }
        contentAsString = sb.toString();
      } catch (Exception e) {
        LeXiaoXiaoBanLog.e(TAG, e.toString());
      }

      // Makes sure that the InputStream is closed after the app is
      // finished using it.
    } catch (MalformedURLException e) {
      LeXiaoXiaoBanLog.e(TAG, "exception" + e.toString());
      e.printStackTrace();
    } catch (IOException e) {
      LeXiaoXiaoBanLog.e(TAG, "exception" + e.toString());
      e.printStackTrace();
    } finally {
      if (is != null) {
        is.close();
      }
      if (conn != null) {
        conn.disconnect();
      }
      LeXiaoXiaoBanLog.e(TAG, "finally");
    }

    return new JSONObject(AES128.decrypt(contentAsString));
  }

  public static final JSONObject initiateHttpConnection(String myurl,
      String methodName) throws IOException, JSONException {
    LeXiaoXiaoBanLog.e(TAG, "URL:" + myurl);
    LeXiaoXiaoBanLog.e(TAG, "REQUEST METHOD:" + methodName);

    InputStream is = null;
    String contentAsString = "";// = convertStreamToString(is);
    HttpURLConnection conn = null;
    try {
      int splitIndex = myurl.indexOf('?');
      String urlPart = myurl.substring(0, splitIndex);
      String argumentPart = myurl.substring(splitIndex + 1, myurl.length());
      URL url = new URL(myurl);
      LeXiaoXiaoBanLog.e(TAG, urlPart.toString());
      LeXiaoXiaoBanLog.e(TAG, argumentPart.toString());
      conn = (HttpURLConnection) url.openConnection();
      conn.setReadTimeout(TIMEOUT * 5 /* milliseconds */);
      conn.setConnectTimeout(TIMEOUT /* milliseconds */);
      conn.setRequestMethod(methodName);
      conn.setUseCaches(USE_SYSTEM_CACHE);
      LeXiaoXiaoBanLog.e(TAG, methodName);
      conn.setDoInput(true);
      // conn.setDoOutput(true);
      conn.setInstanceFollowRedirects(false);
      // Starts the query
      try {
        // DataOutputStream wr = new DataOutputStream(conn.getOutputStream ());
        // wr.writeBytes(argumentPart);
        // wr.flush();
        // wr.close();
        conn.connect();
        int response = conn.getResponseCode();
        LeXiaoXiaoBanLog.e(TAG, "The response is: " + response);
        is = conn.getInputStream();
        // Convert the InputStream into a string
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,
            "UTF-8"), 1024);
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null) {
          sb.append(line + "\n");
        }
        contentAsString = sb.toString();
      } catch (Exception e) {
        LeXiaoXiaoBanLog.e(TAG, e.toString());
      }

      // Makes sure that the InputStream is closed after the app is
      // finished using it.
    } catch (MalformedURLException e) {
      LeXiaoXiaoBanLog.e(TAG, "exception" + e.toString());
      e.printStackTrace();
    } catch (IOException e) {
      LeXiaoXiaoBanLog.e(TAG, "exception" + e.toString());
      e.printStackTrace();
    } finally {
      if (is != null) {
        is.close();
      }
      if (conn != null) {
        conn.disconnect();
      }
      LeXiaoXiaoBanLog.e(TAG, "finally");
    }
    return new JSONObject(contentAsString);
  }

  public static final JSONObject initiateHttpConnection(String myurl,
      String methodName, boolean useProxy) throws IOException, JSONException {
    LeXiaoXiaoBanLog.e(TAG, "URL:" + myurl);
    LeXiaoXiaoBanLog.e(TAG, "REQUEST METHOD:" + methodName);

    InputStream is = null;
    String contentAsString = "";// = convertStreamToString(is);
    HttpURLConnection conn = null;
    try {
      int splitIndex = myurl.indexOf('?');
      String urlPart = myurl.substring(0, splitIndex);
      String argumentPart = myurl.substring(splitIndex + 1, myurl.length());
      URL url = new URL(myurl);
      LeXiaoXiaoBanLog.e(TAG, urlPart.toString());
      LeXiaoXiaoBanLog.e(TAG, argumentPart.toString());
      Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
          "115.182.63.48", 80));
      if (useProxy) {
        conn = (HttpURLConnection) url.openConnection(proxy);
      } else {
        conn = (HttpURLConnection) url.openConnection();
      }
      // conn.setRequestProperty("content-type",
      // "application/x-java-serialized-object");
      // conn.setRequestProperty("content-type",
      // "application/x-www-form-urlencoded;charset=UTF-8");
      conn.setRequestProperty("charset", "UTF-8");
      conn.addRequestProperty("Cache-Control", "max-age=0");
      conn.setReadTimeout(TIMEOUT * 5 /* milliseconds */);
      conn.setConnectTimeout(TIMEOUT /* milliseconds */);
      conn.setRequestMethod(methodName);
      conn.setUseCaches(false);
      LeXiaoXiaoBanLog.e(TAG, methodName);
      conn.setDoInput(true);
      // conn.setDoOutput(true);
      conn.setInstanceFollowRedirects(false);
      // Starts the query
      try {
        // DataOutputStream wr = new DataOutputStream(conn.getOutputStream ());
        // wr.writeBytes(argumentPart);
        // wr.flush();
        // wr.close();
        conn.connect();
        int response = conn.getResponseCode();
        LeXiaoXiaoBanLog.e(TAG, "The response is: " + response);
        is = conn.getInputStream();
        // Convert the InputStream into a string
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,
            "UTF-8"), 1024);
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null) {
          sb.append(line + "\n");
        }
        contentAsString = sb.toString();
      } catch (Exception e) {
        LeXiaoXiaoBanLog.e(TAG, e.toString());
      }

      // Makes sure that the InputStream is closed after the app is
      // finished using it.
    } catch (MalformedURLException e) {
      LeXiaoXiaoBanLog.e(TAG, "exception" + e.toString());
      e.printStackTrace();
    } catch (IOException e) {
      LeXiaoXiaoBanLog.e(TAG, "exception" + e.toString());
      e.printStackTrace();
    } finally {
      if (is != null) {
        is.close();
      }
      if (conn != null) {
        conn.disconnect();
      }
      LeXiaoXiaoBanLog.e(TAG, "finally");
    }
    return new JSONObject(contentAsString);
  }

  public static String readIt(InputStream stream, int len) throws IOException,
      UnsupportedEncodingException {
    Reader reader = null;
    reader = new InputStreamReader(stream, "UTF-8");
    char[] buffer = new char[len];
    reader.read(buffer);
    return new String(buffer);
  }

  @SuppressWarnings("resource")
  public static String convertStreamToString(InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
  }

  public static int getCode(JSONObject response) {
    int code;
    try {
      code = response.getInt(TAG_CODE_O);
    } catch (JSONException e) {
      e.printStackTrace();
      return -1;
    }
    return code;
  }

  public static int getStatus(JSONObject response) {
    int status;
    try {
      status = response.getInt(TAG_STATUS_O);
    } catch (JSONException e) {
      e.printStackTrace();
      return -1;
    }
    return status;
  }

  public static ResponseResult operateDevice(String sno, String key,
      String act, String op, int videoId, int uid, int volume, int minutes,
      int ptype, String resourceType) {
    String httpURL = null;
    Uri.Builder b = Uri.parse(API_URL + OPERATE_DEVICE_METHOD_GET).buildUpon();
    b.appendQueryParameter(TAG_SNO_I, sno);
    b.appendQueryParameter(TAG_ACTION_I, act);
    b.appendQueryParameter(TAG_OPERATION_I, op);
    b.appendQueryParameter("type", resourceType);
   // b.appendQueryParameter("mode", "im");

    if (videoId != -1) {
      b.appendQueryParameter(TAG_VIDEO_ID_I, String.valueOf(videoId));
    }
    if (uid != -1) {
      b.appendQueryParameter("uid", String.valueOf(uid));
    }
    if (volume != -1) {
      b.appendQueryParameter(TAG_VOLUME, String.valueOf(volume));
    }
    if (minutes != -1) {
      b.appendQueryParameter(TAG_MINUTE_I, String.valueOf(minutes));
    }
    if (ptype != -1) {
      b.appendQueryParameter(TAG_PLAY_MODE, String.valueOf(ptype));
    }
    httpURL = b.appendQueryParameter(TAG_KEY_I, key).build().toString();

    return commonResult(httpURL, TAG_GET_REQUEST);
  }

  public static String getData(JSONObject response) {
    String data;
    try {
      data = response.getString(TAG_DATA_O);
    } catch (JSONException e) {
      e.printStackTrace();
      return null;
    }
    return data;
  }
}
